<template>
    <n-button v-if="role !== 0" @click="insertActivity">新增</n-button>
    <n-list v-if="dataList.length">
        <n-list-item v-for="item in dataList">
            <template v-if="item.image" #prefix>
                <n-space>
                    <n-image v-for="url in getImgs(item.image)" width="100" :src="url" />
                </n-space>
            </template>
            <template v-if="role >= item.grade" #suffix>
                <n-space>
                    <n-button type="info" @click="editClick(item)">编辑</n-button>
                    <n-button type="error" @click="deleteClick(item)">删除</n-button>
                </n-space>
            </template>
            <n-thing :title="item.title" :title-extra="`${item.grade <= 2 ? '社区级' : item.grade === 3 ? '区(县)级' : '市级'}`">
                <div class="editor" v-html="item.content"></div>
                <n-space>
                    <n-gradient-text type="info">
                        作者：{{ item.createName }}
                    </n-gradient-text>
                    <n-gradient-text type="error">
                        发布于：
                        <n-time :time="new Date(item.createdAt)" />
                    </n-gradient-text>
                    <n-gradient-text type="success">
                        最后编辑时间：
                        <n-time :time="new Date(item.updatedAt)" />
                    </n-gradient-text>
                </n-space>
            </n-thing>
        </n-list-item>
    </n-list>
    <n-pagination
        v-if="pageInfo.total.value > 0"
        v-model:page="pageInfo.pageNum.value"
        v-model:page-size="pageInfo.pageSize.value"
        :item-count="pageInfo.total.value"
        :on-update:page="updatePageNum"
        :on-update:page-size="updatePageSize"
    />
    <n-empty v-if="!dataList.length" description="你什么也找不到" />
    <n-modal
        preset="dialog"
        title="新增活动"
        style="width: 50%"
        positive-text="确定"
        negative-text="取消"
        @positive-click="clickOk"
        @negative-click="clickCancel"
        v-model:show="showModal">
        <n-form
            ref="formRef"
            :label-width="80"
            :model="form"
            :rules="rules"
            size="medium">
            <n-form-item label="标题" path="title">
                <n-input v-model:value="form.title" maxlength="30" placeholder="请输入" show-count clearable />
            </n-form-item>
            <n-form-item label="活动指引图" path="image">
                <x-upload @value-change="valueChange" :max="5" :value="form.image" />
            </n-form-item>
            <n-form-item label="活动内容" path="content">
                <XEditor v-model="form.content" />
            </n-form-item>
        </n-form>
    </n-modal>
</template>
<script setup lang="ts">
import XEditor from '@/components/XEditor/index.vue';
import {ref, reactive, shallowRef, onMounted, computed} from 'vue';
import {EyeOutlined, UserOutlined, FieldTimeOutlined} from '@vicons/antd';
import {page, insert, update, deleteById} from '@/api/activity';
import {userStore} from '@/store/modules/user';
import {formInfo, rulesInfo} from "./types";
import {getImageUrl} from "@/utils/wish";
import {FormInst} from "naive-ui";

const store = userStore();
const role = computed(() => store.role);
const eysIcon = shallowRef(EyeOutlined);
const userIcon = shallowRef(UserOutlined);
const timeIcon = shallowRef(FieldTimeOutlined);
const showModal = ref(false);
const rules = ref(rulesInfo);
let form = reactive<any>(formInfo);
const formRef = ref<FormInst | null>(null);
const dataList = ref([]);
const content = ref();
const pageInfo = {
    pageNum: ref(1),
    pageSize: ref(2),
    total: ref(0),
}
onMounted(() => {
    loadData();
});

const updatePageNum = (pageNum: number) => {
    pageInfo.pageNum.value = pageNum;
    loadData();
}

const updatePageSize = (pageSize: number) => {
    pageInfo.pageSize.value = pageSize;
    loadData();
}

const loadData = async () => {
    const {rows, total}: any = await page({ pageNum: pageInfo.pageNum.value, pageSize: pageInfo.pageSize.value });
    dataList.value = rows;
    pageInfo.total.value = total;
}

const insertActivity = () => {
    showModal.value = true;
    form.image = null;
    form.content = null;
    form.title = null;
}

const clickOk = async () => {
    form.grade = role;
    const valid = await formRef.value?.validate();
    if (!valid) {
        if (!form.id) {
            const {code, message}: any = await insert(form);
            if (code === 200) {
                window.$message.success(message);

            }
        } else {
            const {code, message}: any = await update(form);
            if (code === 200) {
                window.$message.success(message);
            }
        }
        showModal.value = false;
        await loadData();
    }
}

const valueChange = (data: string[]) => {
    form.image = data.join(',');
}

const clickCancel = () => {
    showModal.value = false;
}

const contentChange = (res: string) => {
    console.log(res);
}

const getImgs = (image: string) => {
    if (image) {
        return image.split(',').map((i: string) => (getImageUrl(i)));
    }
}

const deleteClick = (row: any) => {
    window.$dialog.warning({
        title: '警告',
        content: `是否删除标题为'${row.title}'的活动？`,
        positiveText: '是',
        negativeText: '否',
        onPositiveClick: () => {
            deleteById(row.id).then((res) => {
                loadData();
            });
        },
    });
}

const editClick = (row: any) => {
    form.title = row.title;
    form.image = row.image;
    form.content = row.content;
    form.id = row.id;
    showModal.value = true;
}

</script>
<style lang="scss" scoped>
.n-pagination {
    float: right;
}
</style>
